package com.far.game.xiuzhen.gm.web.api.admin;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.far.game.xiuzhen.common.database.entity.DictCharProp;
import com.far.game.xiuzhen.common.database.entity.Partner;
import com.far.game.xiuzhen.common.database.entity.Servers;
import com.far.game.xiuzhen.common.database.entity.Vo.PartnerVo;
import com.far.game.xiuzhen.common.database.entity.Vo.admin.PartnersVo;
import com.far.game.xiuzhen.common.utils.game.ImportPartnerUtil;
import com.far.game.xiuzhen.gm.web.BaseController;
import com.far.game.xiuzhen.service.IPartnerService;
import com.far.game.xiuzhen.service.IServersService;
import com.far.tools.net.http.ReqParamWrapper;
import com.far.tools.net.http.transfer.ResultData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author mike
 * @since 2022-07-20
 */
@Api(tags = "伙伴角色层")
@RestController
@RequestMapping("/api/admin/partner")
public class PartnerController extends BaseController {


    @Autowired
    @Qualifier("partnerServiceImpl")
    private IPartnerService iPartnerService;


    @Autowired
    @Qualifier("serversServiceImpl")
    private IServersService iServersService;

    /**
     * 用户角色表数据新增
     */

    @ApiOperation(value = "伙伴基础数据新增", notes = "伙伴基础数据新增")
    @PostMapping(value = "partner-add")
    private ResultData<String> PartnerAdd(@RequestBody Partner partner) {
        String name = this.getVisitor().getUserName();
        partner.setCreateBy(name);
        partner.setUpdateBy(name);
        if (iPartnerService.save(partner)) {
            return ResultData.ok("添加成功");
        }
        return ResultData.error("添加失败");
    }

    /**
     * 用户角色表数据更新
     */
    @ApiOperation(value = "伙伴基础数据更新", notes = "伙伴基础数据更新")
    @PostMapping(value = "partner-update")
    private ResultData<String> PartnerUpdate(@RequestBody Partner partner) {
        partner.setUpdateBy(this.getVisitor().getUserName());
        if (iPartnerService.updateById(partner)) {
            return ResultData.ok("更新成功");
        }
        return ResultData.error("更新失败");
    }

    /**
     * 用户角色表数据删除
     */
    @ApiOperation(value = "伙伴基础数据删除", notes = "伙伴基础数据删除")
    @ApiImplicitParam(name = "tid", value = "ID", required = true, paramType = "query", dataType = "Integer")
    @GetMapping(value = "partner-remove")
    private ResultData<String> Remove(@RequestParam("tid") Integer tid) {
        if (iPartnerService.removeById(tid)) {
            return ResultData.ok("删除成功");
        }
        return ResultData.error("删除失败");
    }

    /**
     * 用户角色表数据查询
     */
    @ApiOperation(value = "伙伴基础数据查询", notes = "ReqParamWrapper")
    @PostMapping(value = "query")
    private ResultData<IPage<PartnersVo>> Query(@RequestBody ReqParamWrapper<Partner, String> reqParamWrapper) {
        IPage<Partner> iPage = reqParamWrapper.pageLists(iPartnerService);
        List<Partner> partners = iPage.getRecords();
        List<PartnersVo> partnersVoList = partners.stream().map(e -> {
            PartnersVo partnersVo = BeanUtil.copyProperties(e, PartnersVo.class).bulid();
            return partnersVo;
        }).collect(Collectors.toList());
        partnersVoList.stream().map(e -> {
            Servers servers = iServersService.lambdaQuery().eq(Servers::getTid, e.getDomainId()).one();
            Servers servers1 = iServersService.lambdaQuery().eq(Servers::getTid, servers.getParentTid()).one();
            if (ObjectUtil.isEmpty(servers)) {
                return ResultData.error(String.format("%s<%s> 没有绑定正确的区服！", e.getPartnerName(), e.getSid()));
            } else {
                if (ObjectUtil.isEmpty(servers1)) {
                    e.setDomainIdStr(servers.getServerName() + "," + "未绑定服务器");
                } else {
                    e.setDomainIdStr(servers.getServerName() + "," + servers1.getServerName());
                }
            }
            return e;
        }).collect(Collectors.toList());

        IPage<PartnersVo> page = new Page<>();
        page.setSize(iPage.getSize());
        page.setCurrent(iPage.getCurrent());
        page.setTotal(iPage.getTotal());
        page.setRecords(partnersVoList);


        if (iPage.getRecords().size() == 0) {
            return ResultData.error("暂无数据");
        }
        return ResultData.ok(page);
    }

    @ApiOperation(value = "伙伴数据导入", notes = "伙伴数据表导入")
    @PostMapping("/import")
    public ResultData importExcel(MultipartFile file) {
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());

            HashMap<String, String> headerAlias = new HashMap<>(13);
            headerAlias.put("名称", "partnerName");
            headerAlias.put("职业", "job");
            headerAlias.put("种族", "race");
            headerAlias.put("品质", "quality");
            headerAlias.put("生命", "blood");
            headerAlias.put("攻击", "attack");
            headerAlias.put("物防", "pdef");
            headerAlias.put("法防", "mdef");
            headerAlias.put("命中", "hit");
            headerAlias.put("闪避", "dodge");
            headerAlias.put("暴击", "crit");
            headerAlias.put("抗暴", "revolt");
            headerAlias.put("伙伴介绍", "introduce");
            reader.setHeaderAlias(headerAlias);
            List<PartnerVo> list = reader.read(0, 0, PartnerVo.class);
            //保存

            Long max;
            List<Partner> partnerList = iPartnerService.list();
            if (ObjectUtil.isEmpty(partnerList) || partnerList.size() <= 0) {
                max = 100000000000L;
            } else {
                max = Long.valueOf(partnerList.get(0).getSid());
                for (int i = 0; i < partnerList.size(); i++) {
                    if (max < Long.valueOf(partnerList.get(i).getSid()))
                        max = Long.valueOf(partnerList.get(i).getSid());
                }
            }


            List<Partner> partners = new ArrayList<>();
            for (PartnerVo partnerVo : list) {
                Long sum = max++;
//                Partner partner = new Partner();
                if (ObjectUtil.isEmpty(partnerVo.getJob())) {

                    return ResultData.error("职业数据不能为空");
                }
                Partner partner1 = ImportPartnerUtil.calculateBattleAttr(partnerVo);
                Partner partner = BeanUtil.copyProperties(partner1, Partner.class);
                partner.setSid(sum.toString());
                partners.add(partner);
            }

            iPartnerService.saveBatch(partners);
            return ResultData.ok("导入成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultData.error("导入失败！");
    }


    @ApiOperation(value = "伙伴数据导出", notes = "数据库导出伙伴数据")
    @GetMapping("/eptExcel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        //查询所有数据
        List<Partner> list = iPartnerService.list();
        //通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.addHeaderAlias("名称", "partnerName");
        writer.addHeaderAlias("职业", "job");
        writer.addHeaderAlias("种族", "race");
        writer.addHeaderAlias("品质", "quality");
        writer.addHeaderAlias("生命", "blood");
        writer.addHeaderAlias("攻击", "attack");
        writer.addHeaderAlias("物防", "pdef");
        writer.addHeaderAlias("法防", "mdef");
        writer.addHeaderAlias("命中", "hit");
        writer.addHeaderAlias("闪避", "dodge");
        writer.addHeaderAlias("暴击", "crit");
        writer.addHeaderAlias("抗暴", "revolt");
        writer.setOnlyAlias(true);


        //默认配置
        writer.write(list, true);
        //设置content—type
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");

        //设置标题
        String fileName = URLEncoder.encode("伙伴数据", "UTF-8");
        //Content-disposition是MIME协议的扩展，MIME协议指示MIME用户代理如何显示附加的文件。
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream outputStream = response.getOutputStream();

        //将Writer刷新到OutPut
        writer.flush(outputStream, true);
        outputStream.close();

    }

}

